package com.steven.ourcontest.collect.api

import com.steven.ourcontest.collect.bean.TeamCollectionsRes
import com.steven.ourcontest.contest.bean.MatchCollectionRes
import com.steven.ourcontest.login.helper.LoginController
import com.steven.ourcontest.net.ApiTransformer
import com.steven.ourcontest.net.EmptyResponse
import com.steven.ourcontest.net.NetConstants
import io.reactivex.Observable
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

class CollectApi private constructor() {

    private val mRetrofit: Retrofit
    private val mApiService: CollectApiService

    companion object {
        const val DEFAULT_TIMEOUT = 5
        val instance: CollectApi by lazy {
            CollectApi()
        }
    }

    init {
        val builder = OkHttpClient.Builder()
        builder.connectTimeout(
            DEFAULT_TIMEOUT.toLong(),
            TimeUnit.SECONDS
        )
        builder.addInterceptor {
            val request = it.request()
            val requestBuilder = request.newBuilder()
            requestBuilder.header("uid", LoginController.userId.toString())
                .header("Accept", "application/json")
                .header("userType", LoginController.userType)
            return@addInterceptor it.proceed(requestBuilder.build())
        }
        mRetrofit = Retrofit.Builder()
            .client(builder.build())
            .baseUrl(NetConstants.CHAT_BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build()
        mApiService = mRetrofit.create(CollectApiService::class.java)
    }

    fun queryTeamCollections(lastCreateTime:Long): Observable<TeamCollectionsRes> {
        return mApiService.queryTeamCollections(lastCreateTime).compose(ApiTransformer())
    }

    fun addTeamCollection(teamId:Long): Observable<EmptyResponse> {
        return mApiService.addTeamCollection(teamId).compose(ApiTransformer())
    }

    fun deleteTeamCollection(teamId:Long): Observable<EmptyResponse> {
        return mApiService.deleteTeamCollection(teamId).compose(ApiTransformer())
    }

    fun addMatchCollection(matchId: Long): Observable<EmptyResponse> {
        return mApiService.addMatchCollection(matchId).compose(ApiTransformer())
    }

    fun deleteMatchCollection(matchId: Long): Observable<EmptyResponse> {
        return mApiService.deleteMatchCollection(matchId).compose(ApiTransformer())
    }

    fun selectMatchCollections(lastCreateTime: Long): Observable<MatchCollectionRes> {
        return mApiService.selectMatchCollections(lastCreateTime).compose(ApiTransformer())
    }
}